#include <atomic>
#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>

using boost::asio::ip::tcp;
using namespace std;

class AsyncServer {
public:
	explicit AsyncServer(boost::asio::io_context &io_context) : acceptor_(io_context), timer_(io_context), stopped_(false) {}

	void Start(uint16_t port = 0) {
		tcp::endpoint endpoint(tcp::v4(), port);
		acceptor_.open(endpoint.protocol());
		acceptor_.set_option(tcp::acceptor::reuse_address(true));
		acceptor_.bind(endpoint);
		acceptor_.listen();

		// 获取实际分配的端口
		endpoint = acceptor_.local_endpoint();
		port_    = endpoint.port();

		cout << "Service started on port: " << port_ << endl;

		DoAccept();
	}

	void Stop() {
		if (!stopped_.exchange(true)) {
			acceptor_.close();
			timer_.cancel();
		}
	}

private:
	void DoAccept() {
		if (stopped_) return;

		auto new_session = make_shared<tcp::socket>(acceptor_.get_executor());
		acceptor_.async_accept(*new_session, [this, new_session](const boost::system::error_code &ec) {
			if (!ec) {
				// 处理新连接（示例：简单关闭）
				boost::system::error_code ignored_ec;
				new_session->shutdown(tcp::socket::shutdown_both, ignored_ec);
				new_session->close(ignored_ec);
			}
			DoAccept(); // 继续接受新连接
		});
	}

	tcp::acceptor acceptor_;
	boost::asio::steady_timer timer_;
	atomic<bool> stopped_;
	uint16_t port_;
};

class ServiceManager {
public:
	explicit ServiceManager(size_t thread_pool_size = 4) : work_guard_(io_context_), pool_(thread_pool_size) {
		// 启动I/O上下文线程池
		for (size_t i = 0; i < thread_pool_size; ++i) {
			pool_.create_thread(boost::bind(&boost::asio::io_context::run, &io_context_));
		}
	}

	~ServiceManager() {
		StopAll();
		pool_.join_all();
	}

	void AddService() {
		auto server = make_shared<AsyncServer>(io_context_);
		servers_.emplace_back(server);
		server->Start();
	}

	void StopAll() {
		for (auto &server: servers_) {
			server->Stop();
		}
		io_context_.stop();
	}

private:
	boost::asio::io_context io_context_;
	boost::asio::io_context::work work_guard_;
	boost::thread_group pool_;
	vector<shared_ptr<AsyncServer>> servers_;
};


// g++ -std=c++11 -pthread -o multi_udp_asio.exe multi_udp_asio.cpp
int main() {
	try {
		ServiceManager manager(4); // 4个I/O线程

		// 启动100个服务（示例）
		for (int i = 0; i < 100; ++i) {
			manager.AddService();
			this_thread::sleep_for(chrono::milliseconds(10)); // 避免端口分配冲突
		}

		// 保持运行（实际应添加退出条件）
		this_thread::sleep_for(chrono::seconds(60));
	} catch (const exception &e) {
		cerr << "Exception: " << e.what() << endl;
	}
	return 0;
}
